package cn.com.ccxe.core.io;

import java.io.File;
import java.io.IOException;

import org.apache.http.entity.ByteArrayEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.util.Configurations;

public class MirrorWrite extends AbstractMirrorWrite {

	@SuppressWarnings("unused")
	private Logger 		logger = LoggerFactory.getLogger(MirrorWrite.class);
	private String 		CHARSET = Configurations.getString("mirror.charset", "GBK");
	
	
	public MirrorWrite() {
	}
	
	public MirrorWrite(String charset) {
		if(charset != null && charset.length() > 0) {
			CHARSET = charset;
		}
	}

	public void writeFile(ByteArrayEntity content, String url)
			throws IOException {
		int contentLength = (int)content.getContentLength();
		if(contentLength <= 0) {
			return;
		}
		File directory = new File(getDirectoryPath(url));
		File file = new File(getPath(url));
		
		mkdirs(directory);
		write(content.getContent(), file,contentLength);
	}
	
	@Override
	public void writeFile(String text, String url) throws IOException {
		if (!isEmpty(text) || !isEmpty(url)) {
			return;
		}
		File directory = new File(getDirectoryPath(url));
		File file = new File(getPath(url));
		mkdirs(directory);
		write(text, file, CHARSET);
	}

	private boolean isEmpty(String url) {
		if(url != null && url.length() > 0) {
			return true;
		}
		return false;
	}

}
